﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZDT.Task.Job;
using ZDT.Task.Entity;
using ZDT.Task.Plan;
using ZDT.Task.Data;
using ZDT.Http;
using ZDT.Text;
using ZDT.Common;

namespace ZDT.Task.TGather
{
    public class PublishJob : TaskItemJob<PublishInfo,PublishInfo>
    {
        public PublishJob(PlanItem<PublishInfo> planItem, PublishInfo result)
            : base(planItem, result)
        {
        }
        protected override void Init()
        {
            InitParam();
            base.Init();
            Login();
            for (int k = Result.Index; k <= Result.Datas.Count; k++)
            {
                //GetPageList(k);
                var workItem = new WorkItem<PublishInfo>();
                workItem.Index = k;
                workItem.Params.Add(k);
                workItem.Type = WorkItemType.GetList;
                AddWorkItem(workItem);
            }
        }
        protected override void ExecuteOne(object param)
        {
            base.ExecuteOne(param);
            var workItem = param as WorkItem<PublishInfo>;
            switch (workItem.Type)
            {
                case WorkItemType.Login:
                    Login();
                    break;
                case WorkItemType.Pulish:
                    Publish(Setting.Datas[workItem.Index]);
                    break;
                case WorkItemType.Refresh:
                    break;
                case WorkItemType.Other:
                    break;
                default:
                    break;
            }
        }
        private void InitParam()
        {
            if (Setting.Result==null)
            {
                Setting.Result=new List<SDictionary<string,PublishItem>>();
                foreach (var item in Setting.WebInfos)
                {
                    
                }
            }
        }
        private void Login()
        {
            foreach (var item in Setting.WebInfos)
            {
                var webInfo = item.Value;
                if (!string.IsNullOrEmpty(webInfo.LoginInfo.Url))
                {
                    string html = Url.GetSource(webInfo.LoginInfo.Url, webInfo.Encode, webInfo.LoginInfo.Cookie, p =>
                    {
                        webInfo.LastCookie = p.CookieContainer.GetCookieHeader(p.RequestUri);
                    });
                }
                else if (!string.IsNullOrEmpty(webInfo.LoginInfo.Cookie))
                {
                    webInfo.LastCookie = webInfo.LoginInfo.Cookie;
                }
            }
        }
        private Dictionary<string, PublishItem> Publish(DetailItemInfo data)
        {
            var result = new SDictionary<string, PublishItem>();
            foreach (var item in Setting.WebInfos)
            {
                result.Add(item.Key,Publish(item.Value,data));
            }
            Result.Result.Add(result);
            return result;
        }
        
        private PublishItem Publish(PublishWebInfo webInfo, DetailItemInfo data)
        {
            PublishItem result = new PublishItem();
            result.Data = new SDictionary<string, string>();
            foreach (var item in webInfo.DataRel)
            {
                string value = string.Empty;
                if (data.Deta.ContainsKey(item.Value))
                {
                    value = data.Deta[item.Value];
                }
                result.Data.Add(item.Key, value);
            }
            string url = string.Format("{0}<POST></POST>", webInfo.Url, AllConverter.Dictionary2Url(result.Data));
            string html = Url.GetSource(url, AllConverter.ToEnum<GlobalParas.WebCode>(webInfo.Encode), webInfo.LastCookie);
            if (!string.IsNullOrEmpty(html))
            {
                result.State = "ok";
                result.PublishTime = DateTime.Now;
            }
            if (!string.IsNullOrEmpty(webInfo.UploadFileUrl))
            {
                foreach (var item in data.Files)
                {
                    UploadFile(webInfo.LastCookie,webInfo.UploadFileUrl,item.Value);
                    result.FileList.Add(item.Key, item.Value);
                }
            }
            return result;
        }
        private void UploadFile(string lastCookie,string url, string filePath)
        {
            Url.UploadFile(url, lastCookie, filePath);
        }

        #region Tools
        private string TFilter(string source, GatherRule rule)
        {
            string result = source;
            if (rule != null)
            {
                switch (rule.MatchType)
                {
                    case ZDT.Text.MatchType.Replace:
                        result = Text.StringMatch.Parse(source,rule.StartMark,rule.EndMark,rule.Profix,rule.ReplaceRule,rule.DescPlace);
                        break;
                    case ZDT.Text.MatchType.Match:
                        result = Text.StringMatch.Match(source,rule.Pattern);
                        break;
                    default:
                        break;
                }
            }
            return result;
        }
        private List<string> TFilters(string source, GatherRule rule)
        {
            List<string> result = new List<string>();
            if (rule != null)
            {
                switch (rule.MatchType)
                {
                    case ZDT.Text.MatchType.Replace:
                        string value = Text.StringMatch.Parse(source, rule.StartMark, rule.EndMark, rule.Profix, rule.ReplaceRule, rule.DescPlace);
                        result.Add(value);
                        break;
                    case ZDT.Text.MatchType.Match:
                        var v = new PatternSetting();
                        v.Source = source;
                        v.Pattern = rule.Pattern;
                        var t = Text.StringMatch.Match(v);
                        foreach (var item in t)
                        {
                            result.Add(item.Result);
                        }
                        break;
                    default:
                        break;
                }
            }
            return result;
        }
        private List<Dictionary<string,string>> TFilters(string source, GatherRule rule,List<string> keys)
        {
            var v = new PatternSetting();
            v.Source = source;
            v.Pattern = rule.Pattern;
            var result = StringMatch.Match(v, keys);
            return result;
        }

        public string AttachRoot(string url)
        {
            string result = url;
            if (!url.ToLower().StartsWith(StringMatch.HP))
            {
                if (!url.StartsWith("/"))
                {
                    result += "/";
                }
                result += url;
            }
            return result;
        }
        #endregion
    }
}
